function request(option) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: App.config.baseApi + option.url,
      method: option.method || 'post',
      data: option.data || {},
      header: option.header || {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8' // 默认值
      },
      dataType: 'json',
      success: resolve,
      fail: reject
    })
  })
}

function requestHasToken(option) {
  return new Promise((resolve, reject) => {
    let token = wx.getStorageSync('token')
    if(token==null ||token==''||token==undefined) {
      // loginPage()
    } else {
      token = 'Bearer ' + token
    }
    
    wx.request({
      url: App.config.baseApi + option.url,
      method: option.method || 'post',
      data: option.data || {},
      header: option.header || {
        Authorization: token,
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8' // 默认值
      },
      dataType: 'json',
      success: (res) => {
        if (res.data.code == 401) {
          loginPage()
        } else {
          resolve(res)
        }
      },
      fail: reject
    })
  })
}

function loginPage() {
    wx.redirectTo({
      url: '/pages/login/login?url='+getCurrUrl()
    })
  return false
}
function getCurrUrl() {
  let pages = getCurrentPages(); //获取加载的页面
  let currentPage = pages[pages.length - 1]; //获取当前页面的对象
  let url = currentPage.route; //当前页面url
  let options = currentPage.options; //获取url中所带的参数
  // console.log(url,options);
  
  //拼接url的参数
  let returnurl = '';
  for (let key in options) {
    if(key.trim() !=''&& options[key].trim() != ''){
      let value = options[key]
      returnurl += key + '=' + value + '&';
    }
  }
  // console.log('returnurl', returnurl);
  
  if (returnurl.length>0){
    url += "&"+returnurl
    url = url.substring(0, url.length - 1);
  }
  // console.log(122111, url);
  
  return '/'+url;
}

export {
  request,
  requestHasToken
}

/* export default function request(option) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: option.url,
      method: option.method || 'get',
      data: option.data || {},
      success(res) {
        resolve(res)        
      },
      fail(err) {
        reject(err)
      }
    })
  })
} */